import {
  Body,
  Controller,
  Get,
  Post,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import { AdminService } from './admin.service';
import { Public } from '../../../common/decorators/public.decorator';
import { Request } from 'express';
import { ParamDecryptGuard } from '../../../common/guards/param-decrypt.guard';
import { LoginDto, SaveAdminDto } from './dto/admin.dto';
import { RequirePermission } from '../../../common/decorators/require-permission.decorator';
import {
  PageQueryParam,
  PaginationPipe,
} from '../../../common/pipes/pagination.pipe';
import { Like } from 'typeorm';

@Controller('admin')
export class AdminController {
  constructor(private readonly adminService: AdminService) {}

  @UseGuards(ParamDecryptGuard)
  @Public()
  @Post('login')
  async login(@Body() body: LoginDto, @Req() request: Request) {
    return await this.adminService.login(body, request);
  }

  @RequirePermission('sys:admin:save')
  @Post('save')
  async save(@Body() body: SaveAdminDto) {
    return await this.adminService.save(body);
  }

  @RequirePermission('sys:admin:find')
  @Get('find-page')
  async findPage(
    @Query(PaginationPipe) param: PageQueryParam,
    @Query('username') username?: string,
    @Query('email') email?: string,
  ) {
    const { rows, total } = await this.adminService.findAndCount({
      where: {
        username: username ? Like(`%${username}%`) : undefined,
        email,
      },
      relations: {
        roles: {
          permissions: true,
          menus: true,
        },
      },
      ...param,
    });
    return {
      rows,
      total,
    };
  }
}
